package com.momomian.common.exception;

import com.momomian.common.enums.ResCodeEnum;
import com.momomian.common.model.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

/**
 * @author momomian
 * @version 1.0
 * @date 2020/3/28
 * @description 全局异常捕获
 **/
@Slf4j
@RestControllerAdvice
public class BusinessExceptionHandler {

    /**
     * 全局异常处理，其他异常
     */
    @ExceptionHandler(value = Exception.class)
    public ApiResult<Object> errorGlobalHandler(Exception e) {
        log.error("error msg: ", e);
        return ApiResult.error(ResCodeEnum.FAIL.getCode(), e.getMessage());
    }

    /**
     * 参数检验异常
     * @param ex
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public ApiResult<Object> errorBindHandler(Exception ex) {
        String result = ex.getMessage();
        if (result != null && result.contains("BeanPropertyBindingResult")) {
            String filterPrefix = "message [";
            String message = result.substring(result.lastIndexOf(filterPrefix) + filterPrefix.length(), result.lastIndexOf("]"));
            log.error("return error msg: " + ex.getMessage());
            if (message.toLowerCase().contains("exception")) {
                return ApiResult.error(ResCodeEnum.ERROR3004.getCode());
            } else {
                return ApiResult.error(ResCodeEnum.ERROR3004.getCode(), message);
            }
        }
        return ApiResult.error(ResCodeEnum.ERROR3004.getCode(), ex.getMessage());
    }


    @ExceptionHandler(ValidationException.class)
    public ApiResult<Object> handleValidationException(ValidationException e) {
        log.info(e.getMessage(), e);
        return ApiResult.error(ResCodeEnum.ERROR3023.getCode(), e.getCause().getMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ApiResult<Object> handleConstraintViolationException(ConstraintViolationException e) {
        log.info(e.getMessage(), e);
        return ApiResult.error(ResCodeEnum.ERROR3023.getCode(), e.getCause().getMessage());
    }

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BusinessException.class)
    public ApiResult<Object> handleResultException(BusinessException e) {
        log.info("BusinessException :", e);
        return ApiResult.error(e.getCode(), e.getMsg());
    }


}
